angular.module("module.memberLevel",[])
    .config(['$stateProvider',function ($stateProvider) {
        $stateProvider
            .state('home.memberLevel',{
                url:"/memberLevel",
                templateUrl:"memberLevel/memberLevel.html",
                controller:'MemberLevelController',
                controllerAs:'vm'
            })
    }])
    .controller('MemberLevelController',[function () {
        var vm=this;
        var cardStyle = {};

        /*--通过jQuery选择器来对页面实现渲染--*/
//会员卡列表功能主界面 注入
        $('.level').html(template('level_tmpl', data));

//触发编辑按钮 编辑会员卡主界面 注入
        $('.level .edit').on('click', function(){
            var i = $(this).attr('data-i');
            var vo = i ? data.levelList[i] : {};
            $('.level').hide();
            $('.editlevel').html(template('editlevel_tmpl', {card:vo, levelStyleList: data.styleList})).show();
            $('#yulantu').html(template('ylt_tmpl', vo));
            $.extend(cardStyle, vo);
            cloose();
            upload();
            checkfrom(function(para){
                if (!para.cardStyleId) return toast('请选择会员卡样式');
                $.post('ajaxPostMemberLevel', para, function(res){
                    try{res = JSON.parse(res);}catch(e){}
                    if (!res.succeed) return toast((para.id?'编辑':'创建')+'保存数据失败，失败原因：'+res.message);
                    winAlert({body:(para.id?'编辑':'创建')+'成功',fun:function(){
                        window.location.reload();
                    }, closeFun:function(){
                        window.location.reload();
                    }});
                });
            });
            $(':input[name=levelName]').on('change blur keyup', function(){
                cardStyle.level_name = $(this).val();
                cloose();
            });
            $(':input[name=levelMoney]').on('change blur keyup', function(){
                cardStyle.level_money = $(this).val();
                cloose();
            });
            $('.styles p').on('click', function(){
                cardStyle.stylePicture = $(this).find('img').attr('src');
                cardStyle.card_style_id = $(this).attr('data-id');
                cloose();
                $(this).addClass('active').siblings().removeClass('active');
            });
            if (vo.card_style_id) {
                $('.styles p[data-id='+vo.card_style_id+']').click();
            }
        });

//会员卡主界面 删除会员卡业务
        $('.level .del').on('click', function(){
            var i = $(this).attr('data-i');
            winAlert({
                title:'删除会员卡',
                body:'您确定要删除此会员卡吗？',
                cancel:'取消',
                fun:function(){
                    $.getJSON('ajaxDeleteMemberLevel', {levelId:data.levelList[i].id}, function(res){
                        if (!res.succeed) return toast('删除失败，失败原因：'+res.message);
                        toast('删除成功', 'success');
                        window.location.reload();
                    });
                    return true;
                }
            });
            return false;
        });

//会员卡主界面 充值设置业务
        $('.chongzhi').on('click', function(){
            var i = $(this).attr('data-i');
            var vo = data.levelList[i];
            $.getJSON('rechargeSetting',{levelId:vo.id},  function(res){
                winAlert({
                    title:'充值设置',
                    body:template('chongzhi_tmpl', {card:vo, levelProductList:res.data.levelProductList}),
                    cancel:'取消',
                    fun:function(){
                        return savetr(vo);
                    }
                });
                $('#ranktr .dellist').on('click', function(){
                    $(this).parent().parent().remove();
                });
                $('.addtr').on('click', function(){
                    $('#ranktr tbody').append(template('tr_tmpl', {card:vo}));
                    $('#ranktr .dellist').off().on('click', function(){
                        $(this).parent().parent().remove();
                    });
                    return true;
                });
            });
        });
//添加充值赠送事件业务
        function savetr(vo){
            var para = [];
            $('#ranktr .tr').each(function(i, v){
                var d = {};
                $(this).find(':input').each(function(){
                    var type = $(this).attr('type');
                    var required = $(this).attr('required');
                    var max = $(this).attr('max');
                    var min = $(this).attr('min');
                    var fieldname = $(this).attr('fieldname') || '';
                    var errmsg = $(this).attr('errmsg');
                    var name = $(this).attr('name');
                    var val = $.trim($(this).val());
                    if (required){
                        if (val) {
                            $(this).removeClass('errIput');
                        } else {
                            $(this).addClass('errIput');
                            if (type=='hidden') return toast(errmsg);
                        }
                    }
                    if (max && val && parseInt(max, 10) < parseInt(val, 10)) {
                        $(this).addClass('errIput');
                        return toast(fieldname+'最大值不能大于'+max);
                    }
                    if (min && val && parseInt(min, 10) > parseInt(val, 10)) {
                        $(this).addClass('errIput');
                        return toast(fieldname+'最小值不能小于'+min);
                    }
                    d[name] = val;
                });
                para.push(d);
            });
            if ($('#ranktr').find('.errIput').length > 0) return false;
            return $.post('ajaxPostRechargeSetting', {data:JSON.stringify(para), levelId: vo.id}, function(rs){
                rs = JSON.parse(rs);
                if (!rs.succeed) {
                    toast(rs.message); return false;
                } else {
                    toast('充值设置成功!', 'success'); return true;
                }

            });
        }
        function cloose(){
            $('#card').html(template('card_tmpl', {card:cardStyle}));
        }

//生成上传按钮（上传功能通过插件实现）,并给它附上上传回调——————————————————————————————————————————————————
        function upload(){
            var uploader = WebUploader.create({
                swf: '/public/store/Uploader.swf',auto: true,
                server: '/uploadFile', fileVal: 'uploadFile',
                pick:{label:'<button type="button" class="btn gn_btn" style="height:50px;">上传</button>',id:'#picker'},
                resize: false, // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/*'
                }
            });
            uploader.on('uploadSuccess', function(file, res) {
                if (!res.succeed) return toast('上传失败，失败原因：'+res.message);
                $('#yulantu').html(template('ylt_tmpl', {logo:res.data.url}));
                uploader = null;
                cardStyle.logo = res.data.url;
                cloose();
                upload();
            });
        }
    }]);